import os
import sys
import warnings
from PyQt5.QtWidgets import QApplication  # 添加这一行

# 配置
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
warnings.filterwarnings("ignore", message="pkg_resources is deprecated as an API")


# ==================== 工具函数 ====================
def init_resources():
    """初始化资源目录和默认图片"""
    if not os.path.exists("assets"):
        os.makedirs("assets")

    from PIL import Image
    from config import STATE_IMAGES

    colors = {
        "idle": (0, 255, 0),  # 绿色
        "listening": (0, 0, 255),  # 蓝色
        "thinking": (255, 255, 0),  # 黄色
        "speaking": (255, 0, 0)  # 红色
    }

    for state, path in STATE_IMAGES.items():
        if not os.path.exists(path):
            # 创建纯色图片
            img = Image.new('RGB', (150, 150), color=colors.get(state, (128, 128, 128)))
            img.save(path)


# ==================== 主程序 ====================
def main():
    # 初始化资源
    init_resources()
    
    # 创建 QApplication 实例
    app = QApplication(sys.argv)

    # 导入模块
    from desktop_pet_window import DesktopPetWindow
    from websocket_server import WebSocketServer
    from config import WEBSOCKET_PORT
    from voice_worker import VoiceWorker
    from Tools import voice_management_tool, websocket_tool

    # 初始化组件
    websocket_server = WebSocketServer()
    pet_window = DesktopPetWindow()
    voice_worker = VoiceWorker(pet_window, websocket_server)
    pet_window.voice_worker = voice_worker

    # 设置全局实例
    voice_management_tool.set_global_instances(
        websocket_server=websocket_server,
        voice_worker=voice_worker
    )
    websocket_tool.set_websocket_server(websocket_server)
    websocket_tool.set_voice_worker(voice_worker)

    # 启动服务
    websocket_server.start()
    voice_worker.start()
    pet_window.show()

    print(f"🚀 桌面宠物已启动！WebSocket服务器运行在端口 {WEBSOCKET_PORT}")

    # 保持主线程运行
    try:
        # 使用 QApplication 的事件循环
        return app.exec_()  # 修改这一行
    except KeyboardInterrupt:
        print("\n🛑 程序正在退出...")
    finally:
        # 清理资源
        voice_management_tool.set_shutdown_flag()
        if hasattr(voice_worker, 'quit'):
            voice_worker.quit()
            voice_worker.wait()
        if hasattr(websocket_server, 'stop'):
            websocket_server.stop()


if __name__ == '__main__':
    import time

    sys.exit(main())